import { useState, useCallback } from 'react';
import { useApp } from '../../../contexts/AppContext';
import { NavigationState } from '../types';

export function useBrowser() {
  const { state, dispatch } = useApp();
  const [navigationState, setNavigationState] = useState<NavigationState>({
    canGoBack: false,
    canGoForward: false,
    isLoading: false
  });

  const addTab = useCallback((url: string = 'https://www.google.com') => {
    const newTab = {
      id: Date.now().toString(),
      title: '新建标签页',
      url,
      isActive: true
    };
    dispatch({ type: 'ADD_TAB', payload: newTab });
    return newTab.id;
  }, [dispatch]);

  const closeTab = useCallback((tabId: string) => {
    dispatch({ type: 'CLOSE_TAB', payload: tabId });
  }, [dispatch]);

  const switchTab = useCallback((tabId: string) => {
    dispatch({ type: 'SWITCH_TAB', payload: tabId });
  }, [dispatch]);

  const updateTabUrl = useCallback((tabId: string, url: string) => {
    dispatch({ type: 'UPDATE_TAB_URL', payload: { id: tabId, url } });
  }, [dispatch]);

  const activeTab = state.tabs.find(tab => tab.id === state.activeTabId);

  return {
    tabs: state.tabs,
    activeTab,
    navigationState,
    setNavigationState,
    addTab,
    closeTab,
    switchTab,
    updateTabUrl
  };
}